// src/main/services/request-service.ts
import { ipcMain } from 'electron';
import axios, { AxiosRequestConfig, Method } from 'axios';
import log from 'electron-log';

// ==================== 类型定义 ====================
export interface RequestResult {
  success: boolean;
  data?: any;
  error?: string;
  status?: number;
}

export interface RequestOptions extends AxiosRequestConfig {
  timeout?: number;
}

// ==================== 服务实现 ====================
export class RequestService {
  /**
   * 发送 HTTP GET 请求
   */
  public async get(url: string, options: RequestOptions = {}): Promise<RequestResult> {
    try {
      const response = await axios.get(url, {
        timeout: options.timeout || 10000,
        ...options
      });
      
      return {
        success: true,
        data: response.data,
        status: response.status
      };
    } catch (error: any) {
      log.error('GET 请求失败:', error.message);
      
      return {
        success: false,
        error: error.message,
        status: error.response?.status
      };
    }
  }

  /**
   * 发送 HTTP POST 请求
   */
  public async post(url: string, options: RequestOptions = {}): Promise<RequestResult> {
    try {
      const response = await axios.post(url, options.data, {
        timeout: options.timeout || 10000,
        ...options
      });
      
      return {
        success: true,
        data: response.data,
        status: response.status
      };
    } catch (error: any) {
      log.error('POST 请求失败:', error.message);
      
      return {
        success: false,
        error: error.message,
        status: error.response?.status
      };
    }
  }

  /**
   * 发送 HTTP PUT 请求
   */
  public async put(url: string, options: RequestOptions = {}): Promise<RequestResult> {
    try {
      const response = await axios.put(url, options.data, {
        timeout: options.timeout || 10000,
        ...options
      });
      
      return {
        success: true,
        data: response.data,
        status: response.status
      };
    } catch (error: any) {
      log.error('PUT 请求失败:', error.message);
      
      return {
        success: false,
        error: error.message,
        status: error.response?.status
      };
    }
  }

  /**
   * 发送 HTTP DELETE 请求
   */
  public async delete(url: string, options: RequestOptions = {}): Promise<RequestResult> {
    try {
      const response = await axios.delete(url, {
        timeout: options.timeout || 10000,
        ...options
      });
      
      return {
        success: true,
        data: response.data,
        status: response.status
      };
    } catch (error: any) {
      log.error('DELETE 请求失败:', error.message);
      
      return {
        success: false,
        error: error.message,
        status: error.response?.status
      };
    }
  }

  /**
   * 发送任意 HTTP 方法请求
   */
  public async request(method: Method, url: string, options: RequestOptions = {}): Promise<RequestResult> {
    try {
      const response = await axios({
        method,
        url,
        timeout: options.timeout || 10000,
        ...options,
        // 对于需要数据的方法，从 options.data 提取数据
        ...(method.toLowerCase() !== 'get' && method.toLowerCase() !== 'delete' ? { data: options.data } : {})
      });
      
      return {
        success: true,
        data: response.data,
        status: response.status
      };
    } catch (error: any) {
      log.error(`${method} 请求失败:`, error.message);
      
      return {
        success: false,
        error: error.message,
        status: error.response?.status
      };
    }
  }
}

// ==================== IPC 安全暴露 ====================
export function registerRequestIPC(service: RequestService) {
  ipcMain.handle('request:get', (_, url: string, options?: RequestOptions) =>
    service.get(url, options)
  );

  ipcMain.handle('request:post', (_, url: string, options?: RequestOptions) =>
    service.post(url, options)
  );

  ipcMain.handle('request:put', (_, url: string, options?: RequestOptions) =>
    service.put(url, options)
  );

  ipcMain.handle('request:delete', (_, url: string, options?: RequestOptions) =>
    service.delete(url, options)
  );

  ipcMain.handle('request:send', (_, method: Method, url: string, options?: RequestOptions) =>
    service.request(method, url, options)
  );
}

// ==================== 单例导出 ====================
export const requestService = new RequestService();